import os
import tkinter as tk
from tkinter import filedialog, messagebox
from tkinter import ttk
from core import core_work
from openpyxl import load_workbook
from split_long import split_long
from combine_short import combine_short

file_path = ""
ignore_dict = ""


def sort_ignore_words():
    # 读取文件内容
    with open('ignore_words.txt', 'r') as file:
        lines = file.readlines()

    # 按照每行的首字母顺序排序
    sorted_lines = sorted(lines, key=lambda x: x[0])

    # 打印排序后的内容
    # for line in sorted_lines:
    #     print(line.strip())

    # 重新写入文件
    with open('ignore_words.txt', 'w') as file:
        file.writelines(sorted_lines)

    messagebox.showinfo("Success", "排序完成")


def process_excel():
    global file_path
    file_path = filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx")])
    if file_path:

        file_path_temp = file_path.replace('.xlsx', '')
        if os.path.exists(file_path_temp + '_new.xlsx'):
            messagebox.showwarning('Warning', "处理后的文件已存在，当前读取的是处理后的文件！")
            file_path = file_path_temp + '_new.xlsx'

        core_work(file_path)

        # 处理完后，删除 "_new"
        file_path = file_path.replace('_new', '')

        # 打开文件并逐行读取
        with open('ignore_words.txt', 'r', encoding='utf-8') as file:
            words = [line.strip() for line in file]

        global ignore_dict
        ignore_dict = words

        highlight_uppercase()


def highlight_uppercase():
    srt_file_path = file_path.replace('.xlsx', '_new.srt')
    with open(f'{srt_file_path}', encoding='utf-8') as srt_file:
        srt_text = srt_file.read()

    text_widget.config(state=tk.NORMAL)  # Set to editable state
    text_widget.delete('1.0', tk.END)
    text_widget.insert(tk.END, srt_text)

    # Highlight uppercase letters, skipping words in the ignore dictionary
    start_index = '1.0'
    while True:
        start_index = text_widget.search(r'[A-Z]', start_index, stopindex=tk.END, regexp=True)
        if not start_index:
            break
        end_index = text_widget.search(r'\s|[\n.,;:?!]', start_index, stopindex=tk.END, regexp=True)
        if not end_index:
            end_index = tk.END
        word = text_widget.get(start_index, end_index)

        # Check if the word consists of consecutive uppercase letters forming a word
        while end_index and end_index != tk.END and text_widget.get(end_index, end_index + "+2c").isupper():
            end_index = text_widget.search(r'\s|[\n.,;:?!]', end_index + "+1c", stopindex=tk.END, regexp=True)
            if not end_index:
                end_index = tk.END
            word = text_widget.get(start_index, end_index)

        word = word.strip()
        if word not in ignore_dict:
            text_widget.tag_add('highlight', start_index, end_index)
        start_index = end_index
    # 设置高亮的文本
    text_widget.tag_configure('highlight', foreground='#ed7337')
    # text_widget.tag_config('highlight', background='yellow')
    # text_widget.tag_configure('highlight', background='#274467')

    highlight_ranges = text_widget.tag_ranges("highlight")
    for i in range(0, len(highlight_ranges), 2):
        start_index = highlight_ranges[i]
        end_index = highlight_ranges[i + 1]
        content = text_widget.get(start_index, end_index)
        for word in ignore_dict:
            if word == "I":
                continue
            start_pos = start_index
            while True:
                pos = text_widget.search(word, start_pos, end_index)
                if not pos:
                    break
                start_pos = pos + "+1c"
                text_widget.tag_remove("highlight", pos, pos + "+%dc" % len(word))


def change_lower():
    # 找出所有高亮的词，并将首字母改为小写
    highlight_ranges = text_widget.tag_ranges("highlight")

    # 获取所有highlight范围内的文本并转换为小写
    for i in range(0, len(highlight_ranges), 2):
        start_index = highlight_ranges[i]
        end_index = highlight_ranges[i + 1]
        highlighted_text = text_widget.get(start_index, end_index).lower()
        text_widget.replace(start_index, end_index, highlighted_text)


def save_modified_srt():
    file_path_save = file_path.replace('_new', '')
    file_path_save = file_path_save.replace('.xlsx', '')

    modified_srt = text_widget.get('1.0', tk.END)
    # 先保存
    with open(f'{file_path_save}_new.srt', 'w', encoding='utf-8') as modified_file:
        modified_file.write(modified_srt)

    # 再用它来处理excel
    with open(f'{file_path_save}_new.srt', 'r', encoding='utf-8') as srt_file:
        lines = srt_file.readlines()

    # 收集台词
    subtitle_data = []
    for line in lines:
        line = line.strip()
        if line.isdigit():
            continue
        elif '-->' in line:
            continue
        elif line != '':
            subtitle_data.append(line.strip())

    workbook = load_workbook(f'{file_path}')
    sheet = workbook.active
    e_column = sheet['E']
    # 遍历每个单元格并替换换行符
    flag = -2
    for cell in e_column:
        flag += 1
        if flag == -1:
            continue
        if cell.value:
            cell.value = subtitle_data[flag]

    workbook.save(f'{file_path_save}_new.xlsx')

    messagebox.showinfo("Success", "保存成功")


def add_to_ignore_dict():
    selected_text = text_widget.get(tk.SEL_FIRST, tk.SEL_LAST)  # Get the selected text
    if selected_text.strip():  # Check if there's any selected text
        with open('ignore_words.txt', 'a', encoding='utf-8') as file:
            file.write(selected_text.strip() + '\n')  # Add selected text to the ignore dictionary
        messagebox.showinfo("Success", "已添加到忽略字典")
    else:
        messagebox.showwarning("Warning", "请先选择要添加到忽略字典的文本")


def find_previous_highlight():
    # Get the current cursor position
    cursor_position = text_widget.index(tk.INSERT)
    # Search backwards for the previous tagged text
    prev_highlight = text_widget.tag_prevrange("highlight", cursor_position)
    if prev_highlight:
        text_widget.tag_remove("sel", "1.0", tk.END)
        start, end = prev_highlight
        # Select the previous highlighted text
        text_widget.tag_add("sel", start, end)
        text_widget.see(start)
        text_widget.mark_set(tk.INSERT, start)
    else:
        # Deselect any existing selection
        text_widget.tag_remove("sel", "1.0", tk.END)


def find_next_highlight():
    # Get the current cursor position
    cursor_position = text_widget.index(tk.INSERT)
    # Search forwards for the next tagged text
    next_highlight = text_widget.tag_nextrange("highlight", cursor_position, tk.END)
    if next_highlight:
        text_widget.tag_remove("sel", "1.0", tk.END)
        start, end = next_highlight
        # Select the next highlighted text
        text_widget.tag_add("sel", start, end)
        text_widget.see(start)
        text_widget.mark_set(tk.INSERT, end)
    else:
        # Deselect any existing selection
        text_widget.tag_remove("sel", "1.0", tk.END)


def single_change():
    # Get the currently selected text
    try:
        selected_text = text_widget.get("sel.first", "sel.last")
        # Convert the selected text to lowercase
        selected_text_lowercase = selected_text.lower()
        # Replace the selected text with its lowercase version
        text_widget.replace("sel.first", "sel.last", selected_text_lowercase)
    except Exception:
        messagebox.showwarning("Warning", "请先选择需更改的文本")
        ...


def single_change_and_next():
    single_change()
    find_next_highlight()


# 定义执行保存的函数
def save_and_check(event=None):
    # 在此添加保存操作的代码，调用 save_modified_srt 或其他适当的保存函数
    save_modified_srt()


def main_split_long():
    # print(file_path)
    srt_path = file_path.replace('.xlsx', '_new.srt')
    split_long(srt_path)
    messagebox.showinfo("Success", "已完成拆分")
    highlight_uppercase()


def main_combine_short():
    # print(file_path)
    srt_path = file_path.replace('.xlsx', '_new.srt')
    combine_short(srt_path)
    messagebox.showinfo("Success", "已完成合并")
    highlight_uppercase()


# 创建主窗口
root = tk.Tk()
root.title("SRT Editor")

# 设置主窗口背景色
# root.configure(bg="#1e2228")

# 创建一个Frame来容纳第一行的按钮
button_frame = tk.Frame(root)
button_frame.pack(side=tk.TOP, pady=10)

process_button = tk.Button(button_frame, text="选择文件并处理", command=process_excel)
process_button.pack(side=tk.LEFT, padx=5)

add_to_ignore_button = tk.Button(button_frame, text="添加到忽略字典", command=add_to_ignore_dict)
add_to_ignore_button.pack(side=tk.LEFT, padx=5)

sort_ignore_button = tk.Button(button_frame, text="按字母顺序排序忽略字典", command=sort_ignore_words)
sort_ignore_button.pack(side=tk.LEFT, padx=5)

change_button = tk.Button(button_frame, text="一键改小写", command=change_lower)
change_button.pack(side=tk.LEFT, padx=5)

save_button = tk.Button(button_frame, text="保存修改", command=save_modified_srt)
save_button.pack(side=tk.LEFT, padx=5)
root.bind("<Control-s>", save_and_check)

# 创建一个Frame来容纳第二行的按钮
button_frame2 = tk.Frame(root)
button_frame2.pack(side=tk.TOP, pady=10)

# Add buttons for "Find Previous Highlight" and "Find Next Highlight"
prev_highlight_button = tk.Button(button_frame2, text="查找上一个高亮", command=find_previous_highlight)
prev_highlight_button.pack(side=tk.LEFT, padx=5)

next_highlight_button = tk.Button(button_frame2, text="查找下一个高亮", command=find_next_highlight)
next_highlight_button.pack(side=tk.LEFT, padx=5)

single_change_button = tk.Button(button_frame2, text="单个修改", command=single_change)
single_change_button.pack(side=tk.LEFT, padx=5)

single_change_and_next_button = tk.Button(button_frame2, text="单个修改并找下一个", command=single_change_and_next)
single_change_and_next_button.pack(side=tk.LEFT, padx=5)

# 创建一个Frame来容纳第三行的按钮
button_frame3 = tk.Frame(root)
button_frame3.pack(side=tk.TOP, pady=10)

split_long_button = tk.Button(button_frame3, text="拆分长句", command=main_split_long)
split_long_button.pack(side=tk.LEFT, padx=5)

combine_short_button = tk.Button(button_frame3, text="合并短句", command=main_combine_short)
combine_short_button.pack(side=tk.LEFT, padx=5)

# 添加文本框架
text_frame = tk.Frame(root)
text_frame.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)

# 创建Text控件
text_widget = tk.Text(text_frame, wrap="word", height=20, width=80, undo=True)
text_widget.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

# 设置text控件背景色为#22272e
text_widget.config(bg="#22272e")
# 设置text控件文字颜色为#aab9c6
text_widget.config(fg="#aab9c6")

# text_widget.tag_configure("sel", foreground="#f05840")
text_widget.tag_configure("sel", background="#274467")

# 设置编辑光标的颜色为#6cb6ff
text_widget.config(insertbackground='#6cb6ff')

# 添加滚动条
scrollbar = ttk.Scrollbar(text_frame, orient="vertical", command=text_widget.yview)
scrollbar.pack(side=tk.RIGHT, fill="y")

text_widget.config(yscrollcommand=scrollbar.set)

root.mainloop()
